package com.strive.demo.web.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.strive.common.service.impl.SuperServiceImpl;
import com.strive.common.utils.CommonConverterUtil;
import com.strive.demo.web.listener.StringExcelListener;
import com.strive.demo.web.mapper.ShopFileMapper;
import com.strive.demo.web.mapper.ShopMapper;
import com.strive.demo.web.model.PageInfoModel;
import com.strive.demo.web.model.ShopExcel;
import com.strive.demo.web.model.ShopFile;
import com.strive.demo.web.model.ShopModel;
import com.strive.demo.web.service.IShopService;
import com.strive.demo.web.vo.ShopInfoVo;
import com.strive.fastdfs.config.FdfsConfig;
import com.strive.fastdfs.model.StorePathModel;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: bingcun.chen
 * @Date: 2022/3/11 11:04
 * @Version 1.0
 */
@Service
public class ShopServiceImpl extends SuperServiceImpl<ShopMapper, ShopModel> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ShopFileMapper shopFileMapper;

    @Autowired
    private FdfsConfig fastDfsClientConfig;

    /**
     * 查询商品总数
     *
     * @return
     */
    @Override
    public List<ShopModel> queryShopInfo() {
        return shopMapper.selectList(null);
    }

    /**
     * 删除商品信息
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteShopInfo(Integer id) {
        QueryWrapper<ShopModel> queryWrapper = new QueryWrapper<ShopModel>().eq("id", id);
        return shopMapper.delete(queryWrapper) > 0;
    }

    /**
     * 初始化商品信息
     *
     * @param data
     * @return
     */
    @Override
    public boolean initShopInfo(Integer data) {
        shopMapper.delete(null);
        //获取随机数据
        getRandomShopInfo(data);
        return true;
    }

    /**
     * 查询分页商品数据
     *
     * @param pageInfoModel
     * @return
     */
    @Override
    public Page<ShopModel> queryShopInfoPage(PageInfoModel pageInfoModel) {
        Page<ShopModel> shopModelPage = new Page<>(pageInfoModel.getPageSize(), pageInfoModel.getPageNumber());
        QueryWrapper<ShopModel> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(pageInfoModel.getSearch())) {
            wrapper.like("name", pageInfoModel.getSearch());
        }
        return shopMapper.selectPage(shopModelPage, wrapper);
    }

    /**
     * 上传文件(单个文件上传)
     *
     * @return
     */
    @Override
    public StorePathModel uploadFile(MultipartFile multipartFile) {
        StorePathModel storePathModel = null;
        try {
            storePathModel = fastDfsClientConfig.upload(multipartFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return storePathModel;
    }

    /**
     * 下载文件
     *
     * @param id
     */
    @Override
    public void downLoadFiles(Integer id, HttpServletResponse response) throws IOException {
        QueryWrapper<ShopFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", id);
        List<ShopFile> shopFiles = shopFileMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(shopFiles)) {
            throw new RuntimeException("无文件,无法下载");
        }
        //文件转流操作
        byte[] bytes = fastDfsClientConfig.download(shopFiles.get(0).getShopPath(), new DownloadByteArray());
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(shopFiles.get(0).getShopFile(), "UTF-8"));
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();
    }

    @Override
    public List<String> showShopImg(Integer id) {
        QueryWrapper<ShopFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", id);
        List<ShopFile> shopFiles = shopFileMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(shopFiles)) {
            return new ArrayList<>();
        }
        return shopFiles.stream().map(ns -> ns.getShopFullPath()).collect(Collectors.toList());
    }

    @SneakyThrows
    @Override
    public String importFile(MultipartFile file) {
        EasyExcel.read(file.getInputStream(), ShopExcel.class, new StringExcelListener())
                .doReadAll();
        return "ok";
    }

    @Override
    public Boolean deleteShopFile(String path) {
        try {
            fastDfsClientConfig.delete(path);
        }catch (Exception ex){
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public Boolean addShopInfo(ShopInfoVo shopInfoVo) {
        ShopModel shop = CommonConverterUtil.map(shopInfoVo, ShopModel.class);
        int size = shopMapper.insert(shop);
        return size > 0;
    }

    /**
     * 随机获取数据
     */
    private void getRandomShopInfo(Integer nums) {
        for (int i = 0; i < nums; i++) {
            ShopModel shopModel = ShopModel
                    .builder()
                    .name(randomShop(names.length, names))
                    .address(randomShop(address.length, address))
                    .images(randomShop(images.length, images))
                    .description(randomShop(address.length, address))
                    .build();

            shopMapper.insert(shopModel);
        }
    }

    public String randomShop(Integer number, String[] items) {
        Random random = new Random();
        int num = random.nextInt(number - 1);
        return items[num];
    }

    public static String[] names = {"牙膏", "牙刷", "雨伞", "手巾", "纸巾"};

    public static String[] address = {"摩托罗拉大厦", "望京soho", "朝阳公园", "教育局", "市政府"};

    public static String[] images = {"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F68%2Fc8%2F7d%2F68c87deaf34b1b521135181ebfb12633.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649571898&t=a572cfd8229cc99d9b3b56457b7b82d2",
            "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Ffile02.16sucai.com%2Fd%2Ffile%2F2014%2F0827%2Fc0c92bd51bb72e6d12d5b877dce338e8.jpg&refer=http%3A%2F%2Ffile02.16sucai.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649571348&t=b626d90348e03d577fbb175d1ee3d404",
            "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1111%2F05161Q64001%2F1P516164001-3-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649571898&t=4fc58aed0f98a9874256e32cb8525c3a",
            "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1113%2F032120114622%2F200321114622-4-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649571898&t=39418cd754159bef33669f9cabeda665",
            "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp05%2F1910021010125G2-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1649571898&t=04643c2ce4312effbc5cbbf609b8cd23"};


}
